import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_reactive_value/flutter_reactive_value.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:kudos/config/widget_config.dart';
import 'package:kudos/core/utils/kudo_colors.dart';
import '../../utils/image_resource_helper.dart';
import '../../state/heritage/kite_heritage_entity.dart';

class KiteCultureScreen extends StatefulWidget {
  const KiteCultureScreen({super.key});

  @override
  State<KiteCultureScreen> createState() => _KiteCultureScreenState();
}

class _KiteCultureScreenState extends State<KiteCultureScreen> {
  final ReactiveValueNotifier<int> _selectedTitleIndex =
      ReactiveValueNotifier<int>(0);

  late PageController _pageViewController;

  late List<KiteHeritageEntity> _heritageDataList;

  bool _isButtonSwitching = false;

  @override
  void initState() {
    super.initState();
    _pageViewController = PageController();
    _heritageDataList = KiteHeritageEntity.getAllPredefinedHeritage();
  }

  @override
  void dispose() {
    _selectedTitleIndex.dispose();
    _pageViewController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/main_background.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: Column(
          children: [
            _buildFixedNavigationBar(),
            _buildTitleButtonSection(),
            Expanded(child: _buildContentPageView()),
          ],
        ),
      ),
    );
  }

  Widget _buildFixedNavigationBar() {
    return [
          Icon(
            Icons.arrow_back_ios,
            color: KudoColors.black,
            size: 20.sp,
          ).inkWell(onTap: () => Navigator.of(context).pop()),
          Text('Kite culture and characteristics')
              .fontSize(18.sp)
              .fontFamily(GoogleFonts.lato().fontFamily)
              .fontWeight(FontWeight.w900)
              .textColor(KudoColors.black),
        ]
        .toRow(mainAxisAlignment: MainAxisAlignment.start)
        .paddingHorizontal(16.w)
        .paddingVertical(12.h)
        .safeArea(bottom: false);
  }

  Widget _buildTitleButtonSection() {
    final currentSelectedIndex = _selectedTitleIndex.reactiveValue(context);

    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Row(
        children:
            _heritageDataList.asMap().entries.map((entry) {
              final index = entry.key;
              final heritage = entry.value;
              final isSelected = currentSelectedIndex == index;

              return _buildTitleButton(
                heritage.culturalTitle,
                index,
                isSelected,
              ).paddingRight(index < _heritageDataList.length - 1 ? 10.w : 0);
            }).toList(),
      ),
    );
  }

  Widget _buildTitleButton(String title, int index, bool isSelected) {
    return Container(
          padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 4.h),
          decoration: BoxDecoration(
            color: isSelected ? KudoColors.yellow : KudoColors.green,
            borderRadius: BorderRadius.circular(11.r),
          ),
          child: Text(title)
              .italic()
              .fontSize(14.sp)
              .fontWeight(FontWeight.w600)
              .fontFamily(GoogleFonts.lato().fontFamily)
              .textColor(isSelected ? KudoColors.black : KudoColors.black),
        )
        .configWidget(borderRadius: 11.r)
        .inkWell(onTap: () => _onTitleButtonTapped(index));
  }

  Widget _buildContentPageView() {
    return PageView.builder(
      controller: _pageViewController,
      onPageChanged: _onPageChanged,
      itemCount: _heritageDataList.length,
      itemBuilder: (context, index) {
        return _buildContentPage(_heritageDataList[index]);
      },
    );
  }

  Widget _buildContentPage(KiteHeritageEntity heritage) {
    return SingleChildScrollView(
      padding: EdgeInsets.all(16.w),
      child: [
        _buildTextContentSection(heritage),
        _buildImageDisplaySection(heritage).paddingTop(0.h),
      ].toColumn(crossAxisAlignment: CrossAxisAlignment.start),
    );
  }

  Widget _buildTextContentSection(KiteHeritageEntity heritage) {
    return heritage.contentTextList
        .map((contentItem) {
          final title = contentItem['title'] ?? '';
          final content = contentItem['content'] ?? '';

          return [
            [
              Container(
                width: 5.w,
                height: 5.w,
                decoration: BoxDecoration(
                  color: KudoColors.black,
                  shape: BoxShape.circle,
                ),
              ),
              Text(title)
                  .fontSize(14.sp)
                  .fontWeight(FontWeight.w600)
                  .fontFamily(GoogleFonts.lato().fontFamily)
                  .textColor(KudoColors.black)
                  .expanded(),
            ].toRowSpace(space: 8.w),
            Text(content)
                .fontSize(13.sp)
                .fontFamily(GoogleFonts.lato().fontFamily)
                .textColor(KudoColors.black)
                .paddingTop(6.h)
                .paddingBottom(16.h)
                .paddingLeft(16.w),
          ].toColumn(crossAxisAlignment: CrossAxisAlignment.start);
        })
        .toList()
        .toColumn(crossAxisAlignment: CrossAxisAlignment.start);
  }

  Widget _buildImageDisplaySection(KiteHeritageEntity heritage) {
    return [
      Text('Picture Display')
          .fontSize(18.sp)
          .fontWeight(FontWeight.bold)
          .fontFamily(GoogleFonts.lato().fontFamily)
          .textColor(KudoColors.black),
      heritage.imageResourceList.isNotEmpty
          ? SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Row(
              children:
                  heritage.imageResourceList.asMap().entries.map((entry) {
                    final index = entry.key;
                    final imagePath = entry.value;

                    return _buildImageItem(imagePath).paddingRight(
                      index < heritage.imageResourceList.length - 1 ? 12.w : 0,
                    );
                  }).toList(),
            ),
          ).paddingTop(12.h)
          : Text('No images available')
              .fontSize(14.sp)
              .fontFamily(GoogleFonts.lato().fontFamily)
              .textColor(KudoColors.black)
              .paddingTop(12.h),
    ].toColumn(crossAxisAlignment: CrossAxisAlignment.start);
  }

  Widget _buildImageItem(String imagePath) {
    return Container(
      width: 167.w,
      height: 196.h,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.2),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(10.r),
        child: ImageResourceHelper.buildImageWidget(
          imagePath: imagePath,
          width: 167.w,
          height: 196.h,
          fit: BoxFit.cover,
          errorWidget: Container(
            color: Colors.grey.shade300,
            child: Icon(
              Icons.broken_image,
              size: 40.sp,
              color: Colors.grey.shade600,
            ),
          ),
        ),
      ),
    );
  }

  void _onTitleButtonTapped(int index) {
    _isButtonSwitching = true;
    _selectedTitleIndex.value = index;
    _pageViewController
        .animateToPage(
          index,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeInOut,
        )
        .then((_) {
          _isButtonSwitching = false;
        });
  }

  void _onPageChanged(int index) {
    if (!_isButtonSwitching) {
      _selectedTitleIndex.value = index;
    }
  }
}
